package caom.wangs.java8.lamda;

import caom.wangs.java8.pojo.Apple;
import org.junit.jupiter.api.Test;

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static caom.wangs.java8.streamDemo.DataServer.appleStore;

public class LamdaDemo2 {
    @Test
    public void test1() {
        Stream<Apple> stream = appleStore.stream();

        /**
         * stream has already been operated upon or closed
         * 流不可用被重复使用
         */

        Stream<Apple> appleStream = stream.filter(apple -> apple.getColor().equals("red"));

        Stream<Apple> distinct = stream.distinct();
        Stream<Apple> distinct1 = appleStream.distinct();

    }

    /**
     * 流的三种操作类型
     * 1.生成一个初始流
     * 2.中间操作
     * 3.中止操作
     */
    // 1. 生成一个初始流
    public void initTest() {
        Stream.of("111", "222", "333");
//        Collection.stream(); // List
//        Arrays.Stream();

    }

    //2.中间操作 惰性操作 中间计算操作
    @Test
    public void test2() {
        appleStore.stream().filter(apple -> {
            System.out.println("hello");
            return true;
        }).toArray();
    }

    //3.终止操作 有且只有一个是最后操作， 最终生成结果
    // toArray()  findAny()  。。。 终止操作
    @Test
    public void test3() {
        Object[] hellos = appleStore.stream().filter(apple -> {
            System.out.println("hello");
            return true;
        }).toArray();
    }


    /**
     * 流的执行顺序：
     * 按顺序一个个的去 执行流程
     */

    @Test
    public void test4() {
        Object[] objects = appleStore.stream().peek(apple -> {
                    System.out.println(apple.getColor());//打印颜色
                })
                .peek(a -> System.out.println(a.getOrigin())).toArray();//打印产地

        for (Apple a : appleStore) {
            System.out.println(a.getColor());
            System.out.println(a.getOrigin());
        }

        /**
         * 按照这个逻辑来做的
         */
        for (Apple a : appleStore) {
            System.out.println(a.getColor());
        }

        for (Apple a : appleStore) {
            System.out.println(a.getOrigin());
        }
    }

    @Test
    public void test5() {
        appleStore.stream().filter(apple -> apple.getColor().equals("red"))
                .map(apple -> apple.getOrigin())
                .distinct()
                .count();
    }

    @Test
    public void test6() {
        Map<String, Double> stringDoubleMap
                = appleStore.stream()
                .collect(Collectors.groupingBy(apple -> apple.getColor(), Collectors.averagingDouble(apple -> apple.getWeight())));
        stringDoubleMap.forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });
    }
}
